package core.proto;

import java.awt.BorderLayout;
import java.util.*;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.ToolTipManager;
import javax.swing.TransferHandler;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import core.proto.rightwindow.BoardPane;
import core.proto.rightwindow.WebUtil;
import core.proto.search.FileTreeSearchDocumentListener;
import core.proto.search.QueryLoggerDocumentListener;
import core.proto.search.SearchBar;
import core.proto.search.SearchPopupDocumentListener;
import core.proto.vis.VizDemoRadial;
import core.util.logging.UserLogWriter;
import core.util.logging.constants.Action;
import core.util.logging.constants.Location;
import static app.constants.CollabVizConstants.*;

public class FileTree extends JPanel implements PropertyChangeListener, KeyListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5427196609258056804L;



	/** Search */
	protected static Color SEARCHED_NODE_BACKGROUND_COLOR = Color.LIGHT_GRAY;
	/** Construct a FileTree */
	/** Icons for closed directory folders */
	public static ImageIcon NONCASE_DIR_CLOSED;

	public static ImageIcon COLD_DIR_CLOSED;

	public static ImageIcon CURRENT_DIR_CLOSED;

	public static ImageIcon CURRENT_ALSPACH_DIR_CLOSED;

	public static ImageIcon CURRENT_MIDDLEBROOK_DIR_CLOSED;

	public static ImageIcon CURRENT_RAFFIELD_DIR_CLOSED;

	public static ImageIcon CURRENT_WILMORE_DIR_CLOSED;

	/** icons for open directory folders */
	public static ImageIcon NONCASE_DIR_OPEN;

	public static ImageIcon COLD_DIR_OPEN;

	public static ImageIcon CURRENT_DIR_OPEN;

	public static ImageIcon CURRENT_ALSPACH_DIR_OPEN;

	public static ImageIcon CURRENT_MIDDLEBROOK_DIR_OPEN;

	public static ImageIcon CURRENT_RAFFIELD_DIR_OPEN;

	public static ImageIcon CURRENT_WILMORE_DIR_OPEN;

	/** icons for closed case files */
	public static ImageIcon NONCASE_FILE_CLOSED;

	public static ImageIcon CURRENT_ALSPACH_FILE_CLOSED;

	public static ImageIcon CURRENT_MIDDLEBROOK_FILE_CLOSED;

	public static ImageIcon CURRENT_RAFFIELD_FILE_CLOSED;

	public static ImageIcon CURRENT_WILMORE_FILE_CLOSED;

	public static ImageIcon COLD_FORMAN_FILE_CLOSED;

	public static ImageIcon COLD_KASTANEK_FILE_CLOSED;

	public static ImageIcon COLD_WARING_FILE_CLOSED;

	public static ImageIcon COLD_FISK_FILE_CLOSED;

	public static ImageIcon COLD_MOELLER_FILE_CLOSED;

	public static ImageIcon COLD_STOKES_FILE_CLOSED;

	// public static ImageIcon RED_F;
	// public static ImageIcon BLUE_F;

	/** icons for open case files */
	public static ImageIcon NONCASE_FILE_OPEN;

	public static ImageIcon CURRENT_ALSPACH_FILE_OPEN;

	public static ImageIcon CURRENT_MIDDLEBROOK_FILE_OPEN;

	public static ImageIcon CURRENT_RAFFIELD_FILE_OPEN;

	public static ImageIcon CURRENT_WILMORE_FILE_OPEN;

	public static ImageIcon COLD_FORMAN_FILE_OPEN;

	public static ImageIcon COLD_KASTANEK_FILE_OPEN;

	public static ImageIcon COLD_WARING_FILE_OPEN;

	public static ImageIcon COLD_FISK_FILE_OPEN;

	public static ImageIcon COLD_MOELLER_FILE_OPEN;

	public static ImageIcon COLD_STOKES_FILE_OPEN;

	public static ImageIcon GRAY_OPEN_FOLDER;

	public static ImageIcon GRAY_CLOSED_FOLDER;

	public static ImageIcon GRAY_CLOSED_FILE;

	public static ImageIcon GRAY_OPEN_FILE;

	// public static ImageIcon OPENED_RED;
	// public static ImageIcon OPENED_BLUE;

	public JTree tree = null;
	public static SearchBar searchBar; 

	public int window;
	
	private String oldSearchValue;
	private String newSearchValue;
	
	private boolean searchTimerBool = false;
	private Timer timer = new Timer(0, null);
	
	private String lastEvent = "mouse";

	public FileTree(File dir, final int window)  {
		this.window = window;

				
		// For graying out stuff. 
		GRAY_OPEN_FOLDER = new ImageIcon(Util.getServerResource("resources/img/opengrayfolder.png"));
		GRAY_CLOSED_FOLDER = new ImageIcon(Util.getServerResource("resources/img/grayfolder.png"));
		GRAY_OPEN_FILE = new ImageIcon(Util.getServerResource("resources/img/opengray.png"));
		GRAY_CLOSED_FILE = new ImageIcon(Util.getServerResource("resources/img/grayfile.png"));

		/** initialize icons for closed directory folders */
		NONCASE_DIR_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/greenfolder.png"));
		COLD_DIR_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/bluefolder.png"));
		CURRENT_DIR_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/redfolder.png"));
		CURRENT_ALSPACH_DIR_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/redfolder_shade1.png"));
		CURRENT_MIDDLEBROOK_DIR_CLOSED = new ImageIcon(Util.getServerResource("resources/img/redfolder_shade2.png"));
		CURRENT_RAFFIELD_DIR_CLOSED = new ImageIcon(Util.getServerResource("resources/img/redfolder_shade3.png"));
		CURRENT_WILMORE_DIR_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/redfolder_shade4.png"));

		/** initialize icons for open directory folders */
		NONCASE_DIR_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/opengreenfolder.png"));
		COLD_DIR_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openbluefolder.png"));
		CURRENT_DIR_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openredfolder.png"));
		CURRENT_ALSPACH_DIR_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openredfolder_shade1.png"));
		CURRENT_MIDDLEBROOK_DIR_OPEN = new ImageIcon(Util.getServerResource("resources/img/openredfolder_shade2.png"));
		CURRENT_RAFFIELD_DIR_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openredfolder_shade3.png"));
		CURRENT_WILMORE_DIR_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openredfolder_shade4.png"));

		/** initialize icons for closed case files */
		NONCASE_FILE_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/greenfile.png"));
		CURRENT_ALSPACH_FILE_CLOSED = new ImageIcon(Util.getServerResource("resources/img/redfile_shade1.png"));
		CURRENT_MIDDLEBROOK_FILE_CLOSED = new ImageIcon(Util.getServerResource("resources/img/redfile_shade2.png"));
		CURRENT_RAFFIELD_FILE_CLOSED = new ImageIcon(Util.getServerResource("resources/img/redfile_shade3.png"));
		CURRENT_WILMORE_FILE_CLOSED = new ImageIcon(Util.getServerResource("resources/img/redfile_shade4.png"));
		COLD_FORMAN_FILE_CLOSED = new ImageIcon(Util.getServerResource("resources/img/bluefile_shade1.png"));
		COLD_KASTANEK_FILE_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/bluefile_shade2.png"));
		COLD_WARING_FILE_CLOSED = new ImageIcon(Util.getServerResource("resources/img/bluefile_shade3.png"));
		COLD_FISK_FILE_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/bluefile_shade4.png"));
		COLD_MOELLER_FILE_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/bluefile_shade5.png"));
		COLD_STOKES_FILE_CLOSED = new ImageIcon(Util.getServerResource(
		"resources/img/bluefile_shade6.png"));

		/** initialize icons for open case files */
		NONCASE_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/opengreen.png"));
		CURRENT_ALSPACH_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openred_shade1.png"));
		CURRENT_MIDDLEBROOK_FILE_OPEN = new ImageIcon(Util.getServerResource("resources/img/openred_shade2.png"));
		CURRENT_RAFFIELD_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openred_shade3.png"));
		CURRENT_WILMORE_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openred_shade4.png"));
		COLD_FORMAN_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openblue_shade1.png"));
		COLD_KASTANEK_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openblue_shade2.png"));
		COLD_WARING_FILE_OPEN = new ImageIcon(Util.getServerResource("resources/img/openblue_shade3.png"));
		COLD_FISK_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openblue_shade4.png"));
		COLD_MOELLER_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openblue_shade5.png"));
		COLD_STOKES_FILE_OPEN = new ImageIcon(Util.getServerResource(
		"resources/img/openblue_shade6.png"));

		setLayout(new BorderLayout());

		// Make a tree list with all the nodes, and make it a JTree
		DefaultMutableTreeNode root = addNodes(null, dir, 0);
		IconData data = (IconData) root.getUserObject();
		((CaseNode) data.getObject()).markAsRoot();

		tree = new JTree(root);
		tree.addTreeExpansionListener(new TreeExpansionListener() {

			@Override
			public void treeCollapsed(TreeExpansionEvent arg0) {
				TreePath selPath = arg0.getPath();
				CaseNode caseNode = null;
				if (selPath != null) {
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath
					.getLastPathComponent();
					IconData icon = (IconData) node.getUserObject();
					caseNode = (CaseNode) icon.getObject();
				}
				
				if(lastEvent.equals("key")){
					System.out.println("WHAT DO YOU WANT");
					writeLog(Action.KEYTYPE, "Directory Tree", caseNode.getName(), "null");
				}
				else if(lastEvent.equals("mouse")){
					writeLog(Action.CLICK, "Directory Tree", caseNode.getName(), "null");
				}
			}

			@Override
			public void treeExpanded(TreeExpansionEvent arg0) {
				TreePath selPath = arg0.getPath();
				CaseNode caseNode = null;
				if (selPath != null) {
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath
					.getLastPathComponent();
					IconData icon = (IconData) node.getUserObject();
					caseNode = (CaseNode) icon.getObject();
				}
				
				if(lastEvent.equals("key")){
					System.out.println("WHAT DO YOU WANT");
					writeLog(Action.KEYTYPE, "Directory Tree", caseNode.getName(), "null");
				}
				else if(lastEvent.equals("mouse")){
					writeLog(Action.CLICK, "Directory Tree", caseNode.getName(), "null");
				}
			}
			
		});
		FilterTreeModel model = new FilterTreeModel((FilterTreeNode) tree.getModel().getRoot());
		tree.setModel(model);
		tree.setDragEnabled(true);
		tree.getSelectionModel().setSelectionMode(
				TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
		tree.setTransferHandler(new FileTransferHandler());

		Vector<String> directorypath = new Vector();
		TreeCellRenderer renderer = new IconCellRenderer();
		tree.setCellRenderer(renderer);
		ToolTipManager.sharedInstance().registerComponent(tree);

		tree.addKeyListener(this);
		
		/**
		 * add listener to tree for mouse click event, distinguish between
		 * single and double click
		 */
		tree.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				// for transferHandler
				
				lastEvent = "mouse";
				
				JComponent comp = (JComponent) e.getSource();
				TransferHandler handler = comp.getTransferHandler();
				handler.exportAsDrag(comp, e, TransferHandler.COPY_OR_MOVE);

				int selRow = tree.getRowForLocation(e.getX(), e.getY());
				TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
				CaseNode caseNode = null;
				if (selPath != null) {
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath
					.getLastPathComponent();
					IconData icon = (IconData) node.getUserObject();
					caseNode = (CaseNode) icon.getObject();

					if (selRow != -1 && e.getClickCount() >= 2
							&& node.getUserObject() instanceof IconData) {
						if (node.isLeaf() != true) {
							// If isVisited was false, repaint with visited
							// set icons for nonleaf nodes
							if (caseNode.isVisited() == false) {
								caseNode.setVisited(true);
								icon.useExpandedIcon();
							}
						}
						if (node.isLeaf() == true) {
							// If isVisited was false, repaint with visited
							// icons
							if (caseNode.isVisited() == false) {
								caseNode.setVisited(true);
								icon.useExpandedIcon();
							}
							try {
								AllComponents.fileTreeUpdateDoc(caseNode);
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						} 
						else {
							if (node.isLeaf() == true) {
								// node.setVisited(true);
							}
						}
						
						System.out.println("click directory");
						writeLog(Action.DOUBLECLICK, "Directory Tree", caseNode.getName(), "null");
					}
					if(e.getClickCount() == 1 && selPath != null){
						writeLog(Action.CLICK, "Directory Tree", caseNode.getName(), "null");
					}
				}
				
				
				// record clicks on nodes. 
				String nodeName = caseNode == null ? "" : caseNode.toString();
				if (! nodeName.equals("")){
					///UserLogWriter.log2(nodeName, Location.Directory, Action.getClicks(e.getClickCount()));
					
				}
				
			} 
		});

		JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

		// SearchBar
		// SearchBar searchBar = new SearchBar( this );
		searchBar = new SearchBar();
		searchBar.addDocumentListener(new FileTreeSearchDocumentListener(this));
		searchBar.addDocumentListener(new QueryLoggerDocumentListener(Location.Directory));
		searchBar.addDocumentListener(new SearchPopupDocumentListener(searchBar, "Clear search text to see entire directory"));
		searchBar.addPropertyListenerSearchField(this);
		searchBar.setBackground(Color.white);
		searchBar.getSearchField().addKeyListener(this);
		searchBar.addUserLogClickListener(Location.Directory);
		oldSearchValue = "";
		newSearchValue = "";
		
		 
		 
		
		new Thread(
	            new Runnable() {
	                public void run() {
	                	while(true){
	                		//System.out.println("running");
	                		if(searchTimerBool){
	                			System.out.println("hello?");
	                			
	                		}
	                		
	                		/*newSearchValue = searchBar.getSearchField().getText();
	                		if(newSearchValue!= null){
		                		if(!newSearchValue.equals(oldSearchValue)){
		                			synchronized(SearchPopupDocumentListener.popupLock){
		                				VizDemoRadial.setPopupListener(false);
			                			VizDemoRadial.setSearchBarText(newSearchValue);
			                			
			                			
			                			SearchBar docSearch = AllComponents.path2Search.get(AllComponents.getCurrentPath());
			                			
			                					
			                			if(docSearch != null){
			                				docSearch.getSearchField().setText(newSearchValue);
			                			}
			                			oldSearchValue = newSearchValue;
			                			VizDemoRadial.setPopupListener(true);
		                			}
		                		}
	                		}*/
	                	}
	                }
	            }).start();

		JScrollPane scrollPane = new JScrollPane(tree);
		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setBorder(BorderFactory.createEmptyBorder());

		// User log.
		split.setTopComponent(searchBar);
		split.setBottomComponent(scrollPane);
		split.setDividerLocation(-1);
		split.setDividerSize(0); // Hide the ugly divider. 
		split.setEnabled(false);
		this.add(split, BorderLayout.CENTER);
		setSize(scrollPane.getX(), scrollPane.getY() + 100);
	}

	/** Add nodes from under "dir" into curTop. Highly recursive. */
	DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir,
			int type) {
		String curPath = dir.getPath();// get file or folder path zip
		System.out.println("CUR PATH " + curPath);
		DefaultMutableTreeNode curDir;
		if (type == CaseNode.ISDIR) {
			Font font = new Font("Courier New", Font.BOLD, 19);
			curDir = new FilterTreeNode(new IconData(
					NONCASE_DIR_CLOSED, NONCASE_DIR_OPEN, GRAY_OPEN_FOLDER, GRAY_CLOSED_FOLDER, Color.GRAY, font,
					new CaseNode(dir.getName(), curPath, type)));

		} else if (type == CaseNode.ISCOLD) {
			Font font = new Font("Courier New", Font.ITALIC, 12);
			ImageIcon closedIcon = getClosedColdDirIcon(dir.getName());
			ImageIcon openIcon = getOpenColdDirIcon(dir.getName());
			curDir = new FilterTreeNode(new IconData(closedIcon,
					openIcon, GRAY_OPEN_FOLDER, GRAY_CLOSED_FOLDER, Color.GRAY, font, new CaseNode(dir.getName(),
							curPath, type)));
		} else if (type == CaseNode.ISHOT){
			Font font = new Font("Courier New", Font.ITALIC, 12);
			ImageIcon closedIcon = getClosedCurrentDirIcon(dir.getName());
			ImageIcon openIcon = getOpenCurrentDirIcon(dir.getName());
			curDir = new FilterTreeNode(new IconData(closedIcon,
					openIcon, GRAY_OPEN_FOLDER, GRAY_CLOSED_FOLDER, Color.GRAY, font, new CaseNode(dir.getName(),
							curPath, type)));
		} else
			throw new Error("Unknown case node type");

		if (curTop != null) { // should only be null at root
			if (! dir.getAbsolutePath().toLowerCase().contains(".svn")){
				curTop.add(curDir); // add node representing current path
			}
		} 

		Vector ol = new Vector();
		// this only gives the cannonial name of file/dir
		String[] tmp = dir.list();
		for (int i = 0; i < tmp.length; i++) {
			ol.addElement(tmp[i]);
		}
		Collections.sort(ol, new Comparator<String>(){
			// hack to make cover sheet first. 
			public int compare(String left, String right){
				if (left.toLowerCase().contains("cover sheet")){
					return -1;
				}else if (right.toLowerCase().contains("cover sheet")){
					return 1;
				}
				return left.compareTo(right);
			}
		});
		File f;
		Vector files = new Vector();
		// Make two passes, one for Dirs and one for Files. This is #1.
		for (int i = 0; i < ol.size(); i++) {
			// thisObject is a string
			String thisObject = (String) ol.elementAt(i);
			String newPath;
			if (curPath.equals(".")) { // current directory
				// newPath starts from the current directory
				newPath = thisObject;
			} else {
				// new path to the next lv of dir/file
				newPath = curPath + File.separator + thisObject;
			}
			if ((f = new File(newPath)).isDirectory()) {
				if (f.getName().toLowerCase().contains("COLD".toLowerCase())) {
					addNodes(curDir, f, -1);// can change to diff folders if
					// really needed...
				} else if (f.getName().toLowerCase().contains(
						"CURRENT".toLowerCase())) {
					addNodes(curDir, f, 1);
				} else {
					addNodes(curDir, f, 0);
				}
			} else {
				// files in current dir added to "files" vector
				files.addElement(thisObject);
			}
		}
		// Pass two: for files.
		for (int fnum = 0; fnum < files.size(); fnum++) {
			String name = files.elementAt(fnum).toString();
			File currentDir = new File(curPath);
			if (currentDir.getName().toLowerCase().contains(
					"COLD".toLowerCase())) {
				Font font = new Font("Courier New", Font.ITALIC, 12);
				ImageIcon closedIcon = getClosedColdFileIcon(name);
				ImageIcon openIcon = getOpenColdFileIcon(name);
				curDir.add(new FilterTreeNode(new IconData(closedIcon, // BLUE_F,
						openIcon, GRAY_OPEN_FILE, GRAY_CLOSED_FILE, Color.GRAY, font, new CaseNode(files
								.elementAt(fnum).toString(), curPath
								+ File.separator + name, -1))));
			} else if (currentDir.getName().toLowerCase().contains(
					"CURRENT".toLowerCase())) {
				Font font = new Font("Courier New", Font.ITALIC, 12);
				ImageIcon closedIcon = getClosedCurrentFileIcon(currentDir
						.getName());
				ImageIcon openIcon = getOpenCurrentFileIcon(currentDir
						.getName());
				curDir.add(new FilterTreeNode(new IconData(closedIcon, // RED_F,
						openIcon, GRAY_OPEN_FILE, GRAY_CLOSED_FILE, Color.GRAY, font, new CaseNode(files
								.elementAt(fnum).toString(), curPath
								+ File.separator + name, 1))));
			} else {
				Font font = new Font("Courier New", Font.ITALIC, 12);
				curDir.add(new FilterTreeNode(new IconData(
						NONCASE_FILE_CLOSED, NONCASE_FILE_OPEN, GRAY_OPEN_FILE, GRAY_CLOSED_FILE, Color.GRAY,
						font, new CaseNode(files.elementAt(fnum).toString(),
								curPath + File.separator + name, 0))));
			}
		}
		return curDir;
	}

	private ImageIcon getClosedColdDirIcon(String name) {
		ImageIcon icon = COLD_DIR_CLOSED;
		return icon;
	}

	private ImageIcon getOpenColdDirIcon(String name) {
		ImageIcon icon = COLD_DIR_OPEN;
		return icon;
	}

	private ImageIcon getClosedCurrentDirIcon(String name) {
		ImageIcon icon = null;
		if (name.toLowerCase().contains("alspach current"))
			icon = CURRENT_ALSPACH_DIR_CLOSED;
		else if (name.toLowerCase().contains("middlebrook current"))
			icon = CURRENT_MIDDLEBROOK_DIR_CLOSED;
		else if (name.toLowerCase().contains("raffield current"))
			icon = CURRENT_RAFFIELD_DIR_CLOSED;
		else if (name.toLowerCase().contains("wilmore current"))
			icon = CURRENT_WILMORE_DIR_CLOSED;
		else if (name.toLowerCase().contains("current"))
			icon = CURRENT_DIR_CLOSED;
		else
			Util.p("Returning null icon for close dir " + name);
		return icon;
	}

	private ImageIcon getOpenCurrentDirIcon(String name) {
		ImageIcon icon = null;
		if (name.toLowerCase().contains("alspach current"))
			icon = CURRENT_ALSPACH_DIR_OPEN;
		else if (name.toLowerCase().contains("middlebrook current"))
			icon = CURRENT_MIDDLEBROOK_DIR_OPEN;
		else if (name.toLowerCase().contains("raffield current"))
			icon = CURRENT_RAFFIELD_DIR_OPEN;
		else if (name.toLowerCase().contains("wilmore current"))
			icon = CURRENT_WILMORE_DIR_OPEN;
		else if (name.toLowerCase().contains("current"))
			icon = CURRENT_DIR_OPEN;
		else
			Util.p("Returning null icon for open dir " + name);
		return icon;
	}

	private ImageIcon getClosedColdFileIcon(String name) {
		ImageIcon icon = null;
		if (name.toLowerCase().contains("forman"))
			icon = COLD_FORMAN_FILE_CLOSED;
		else if (name.toLowerCase().contains("kastanek"))
			icon = COLD_KASTANEK_FILE_CLOSED;
		else if (name.toLowerCase().contains("waring"))
			icon = COLD_WARING_FILE_CLOSED;
		else if (name.toLowerCase().contains("fisk"))
			icon = COLD_FISK_FILE_CLOSED;
		else if (name.toLowerCase().contains("moeller"))
			icon = COLD_MOELLER_FILE_CLOSED;
		else if (name.toLowerCase().contains("stokes"))
			icon = COLD_STOKES_FILE_CLOSED;
		else
			Util.p("Returning null icon for close cold " + name);
		return icon;
	}

	private ImageIcon getOpenColdFileIcon(String name) {
		ImageIcon icon = null;
		if (name.toLowerCase().contains("forman"))
			icon = COLD_FORMAN_FILE_OPEN;
		else if (name.toLowerCase().contains("kastanek"))
			icon = COLD_KASTANEK_FILE_OPEN;
		else if (name.toLowerCase().contains("waring"))
			icon = COLD_WARING_FILE_OPEN;
		else if (name.toLowerCase().contains("fisk"))
			icon = COLD_FISK_FILE_OPEN;
		else if (name.toLowerCase().contains("moeller"))
			icon = COLD_MOELLER_FILE_OPEN;
		else if (name.toLowerCase().contains("stokes"))
			icon = COLD_STOKES_FILE_OPEN;
		else
			Util.p("Returning null icon for open cold " + name);
		return icon;
	}

	private ImageIcon getClosedCurrentFileIcon(String name) {
		ImageIcon icon = null;
		if (name.toLowerCase().contains("alspach current"))
			icon = CURRENT_ALSPACH_FILE_CLOSED;
		else if (name.toLowerCase().contains("middlebrook current"))
			icon = CURRENT_MIDDLEBROOK_FILE_CLOSED;
		else if (name.toLowerCase().contains("raffield current"))
			icon = CURRENT_RAFFIELD_FILE_CLOSED;
		else if (name.toLowerCase().contains("wilmore current"))
			icon = CURRENT_WILMORE_FILE_CLOSED;
		else
			Util.p("Returning null icon for closed current" + name);
		return icon;
	}

	private ImageIcon getOpenCurrentFileIcon(String name) {
		ImageIcon icon = null;
		if (name.toLowerCase().contains("alspach current"))
			icon = CURRENT_ALSPACH_FILE_OPEN;
		else if (name.toLowerCase().contains("middlebrook current"))
			icon = CURRENT_MIDDLEBROOK_FILE_OPEN;
		else if (name.toLowerCase().contains("raffield current"))
			icon = CURRENT_RAFFIELD_FILE_OPEN;
		else if (name.toLowerCase().contains("wilmore current"))
			icon = CURRENT_WILMORE_FILE_OPEN;
		else
			Util.p("Returning null icon for open current " + name);
		return icon;
	}

	public Dimension getMinimumSize() {
		return new Dimension(100, 560);
	}

	public Dimension getPreferredSize() {
		return new Dimension(100, 560);
	}

	/**
	 * Expands entire tree.
	 * Then also focuses on the current node.  
	 */
	public void expandTree(){
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				for(int i=0; i<tree.getRowCount(); ++i){
					tree.expandRow(i);
				}
			}
		});
		// should refactor this later. 
		this.expandTreeByPath(AllComponents.getCurrentPath(), false);
	}

	public void expandTree(DefaultMutableTreeNode node) {
		// collapseTree();
		TreeNode[] nodes = ((DefaultTreeModel) tree.getModel())
		.getPathToRoot(node);
		TreePath treePath = new TreePath(nodes);
		tree.setSelectionPath(treePath);
		tree.scrollPathToVisible(treePath);
		// make sure all files now have open icon
		for (int i = 0; i < nodes.length; i++) {
			// make all ancestor nodes use expanded icons in the loop, but not
			// working...
			DefaultMutableTreeNode thisnode = (DefaultMutableTreeNode) nodes[i];
			IconData icon = (IconData) thisnode.getUserObject();
			CaseNode case_node = (CaseNode) icon.getObject();
			case_node.setVisited(true);
			icon.useExpandedIcon();
		}
	}

	public void collapseTree() {
		int rowCount = tree.getRowCount() - 1;
		while (rowCount >= 0) {
			tree.collapseRow(rowCount);
			rowCount--;
		}
	}

	/**
	 * This method takes the node string and traverses the tree till it finds
	 * the node matching the string. If the match is found the node is returned
	 * else null is returned
	 * 
	 * @param rotateViz
	 * @param nodeStr
	 *            node string to search for
	 */
	public void expandTreeByPath(String absPath, boolean rotateViz) {

		// Get the enumeration
		Enumeration e = ((DefaultMutableTreeNode) tree.getModel().getRoot())
		.breadthFirstEnumeration();
		// iterate through the enumeration
		while (e.hasMoreElements()) {
			DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) e
			.nextElement();
			IconData icon = (IconData) treeNode.getUserObject();
			CaseNode node = (CaseNode) icon.getObject();
			String filePath = ((CaseNode) node).getAbsolutePath();
			filePath = filePath.replace('/', '\\');

			if (filePath.equals(absPath)) {
				icon.m_backgroudColor = OPEN_FILE_NODE_FOCUS_COLOR;
				this.expandTree(treeNode);
				try {
					AllComponents.fileTreeUpdateDoc(node);
				} catch (IOException e1) {
					e1.printStackTrace();
				} 
				return;
			} 
		}
		tree.repaint();
	}

	public void treeNodeClosedByPath(String absPath) {
		// Get the enumeration
		Enumeration e = ((DefaultMutableTreeNode) tree.getModel().getRoot())
		.breadthFirstEnumeration();
		// iterate through the enumeration
		DefaultMutableTreeNode treeNode = null;
		IconData icon = null;
		CaseNode node = null;
		while (e.hasMoreElements()) {
			treeNode = (DefaultMutableTreeNode) e.nextElement();
			icon = (IconData) treeNode.getUserObject();
			node = (CaseNode) icon.getObject();
			String filePath = ((CaseNode) node).getAbsolutePath();
			filePath = filePath.replace('/', '\\');
			if (filePath.equals(absPath)) {
				break;
			}
		}
		icon.m_backgroudColor = Color.WHITE;
		tree.repaint();
	}

	/**
	 * To remember the tree current expanded status before searching Use it to
	 * return the tree to its original status after searching
	 */
	private List<Integer> savedExpandedRows = new ArrayList<Integer>();

	public List<Integer> getSavedExpandedRows() {
		return savedExpandedRows;
	}

	public void saveTreeExpandedStatus() {
		savedExpandedRows.clear();
		for (int index = 0; index < tree.getRowCount(); index++) {
			if (! tree.isCollapsed(index)) {
				savedExpandedRows.add(new Integer(index));
			}
		}
	}

	public void restoreExpandedTreeStatus() {
		for (Integer row : savedExpandedRows) {
			tree.expandRow(row);
		}
		expandTreeByPath(AllComponents.getCurrentPath(), false);
	}

	public static SearchBar getSearchBar() {
		return searchBar;
	}

	@Override
	public void propertyChange(PropertyChangeEvent arg0) {
		/*if(!searchBar.getSearchField().getText().equals("")){
			VizDemoRadial.setSearchBarText(searchBar.getSearchField().getText());
			
		}
		System.out.println(searchBar.getSearchField().getText());*/
		
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub
		searchTimerBool = false;
		
		lastEvent = "key";
		
		timer.stop();
		
		int delay = 750; //milliseconds
		  ActionListener taskPerformer = new ActionListener() {
		      public void actionPerformed(ActionEvent evt) {
		    	  System.out.println("boolchanged");
		    	 searchTimerBool = true;
		    	 insertSearchQuery();
		      }
		  };
		 timer = new Timer(delay, taskPerformer);
		 timer.setRepeats(false);
		 timer.start();
		
	}

	public void insertSearchQuery(){
		newSearchValue = searchBar.getSearchField().getText();
		synchronized(SearchPopupDocumentListener.popupLock){
			VizDemoRadial.setPopupListener(false);
			VizDemoRadial.setSearchBarText(newSearchValue);
			
			
			SearchBar docSearch = AllComponents.path2Search.get(AllComponents.getCurrentPath());
			
					
			if(docSearch != null){
				docSearch.getSearchField().setText(newSearchValue);
			}
			oldSearchValue = newSearchValue;
			VizDemoRadial.setPopupListener(true);
		}
		searchTimerBool = false;
		
		writeLog(Action.KEYTYPE, "Search Box", "null", newSearchValue.replace(",", "."));
	}
	
	@Override
	public void keyReleased(KeyEvent arg0) {
		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		System.out.println("ever");
		lastEvent = "key";
	}
	
	public void writeLog(Object action, String objectAffected, String objectName, String searchText){
		UserLogWriter.log2(action, "directory", objectAffected, objectName, searchText, "null", "null", "null");
	}
}